#coding=utf-8
import time

class CronRule():
  def setCron(self,ruleString):
    self.ruleString=ruleString
    tokens=ruleString.strip().split()
    if len(tokens)!=5:
      raise exceptions.ValueError('format is error!')
    self.minute=self.analy(tokens[0],0,59)
    self.hour=self.analy(tokens[1],0,23)
    self.day=self.analy(tokens[2],1,31)
    self.month=self.analy(tokens[3],1,12)
    self.week=self.analy((tokens[4]).replace('7','0'),0,6)
    
  def analy(self,exp,start,end):
    result=[]
    tokens=exp.strip().split(',')
    for index in range(len(tokens)):
      subTokens=tokens[index].split('/')
      step=1
      if len(subTokens)>1:
        step=int(subTokens[1])
      areaTokens=subTokens[0].split('-')
      if len(areaTokens)>1:
        start1=int(areaTokens[0])
        end1=int(areaTokens[1])
        if start1>end1:
          data=range(start1,end1+end+1,step)
          for pos in range(len(data)):
            if data[pos]>end:
              data[pos]=data[pos]-end
        else:
          data=range(start1,end1+1,step)
      else:
        if areaTokens[0]=='*':
          if step==1:
            result=['*']
            return result
          else:
            data=range(start,end+1,step)
        else:
          data=[int(areaTokens[0])]
      result[len(result):]=data
    return result
    
    
  def isOnTime(self,currentTime=None):
    if not currentTime:
      currentTime=time.localtime()
#    print self.minute
#    print self.hour
#    print self.day
#    print self.month
#    print self.week
    return self.match(currentTime[4],self.minute) \
            and self.match(currentTime[3],self.hour)\
            and self.match(currentTime[2],self.day) \
            and self.match(currentTime[1],self.month) \
            and self.match(currentTime[6],self.week)
  
  
  def match(self,value, values):
    if values[0]=='*':
      return True
    for v in values:
      if v == value:
        return True
    return False

#rule=CronRule()
#rule.setCron('*/2 2-22/3,7 *,2-8 2-11,* 2')
#print rule.isOnTime()